import 'package:flutter/material.dart';
import '../models/exam_model.dart';
import '../utils/responsive_util.dart';
import 'exam_screen.dart';
import '../services/exam_state_service.dart';
import '../services/image_service.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import '../data/user_data.dart';

class ExamRulesScreen extends StatefulWidget {
  final Exam exam;
  
  const ExamRulesScreen({
    super.key,
    required this.exam,
  });

  @override
  State<ExamRulesScreen> createState() => _ExamRulesScreenState();
}

class _ExamRulesScreenState extends State<ExamRulesScreen> {
  bool _rulesAccepted = false;
  
  // 考试规则列表
  final List<Map<String, dynamic>> _examRules = [
    {
      'icon': Icons.timer,
      'title': '考试时间',
      'description': '考试时间一旦开始将不能暂停，请确保有足够的时间完成考试。',
    },
    {
      'icon': Icons.camera_alt,
      'title': '身份验证',
      'description': '开始考试后，系统将要求您进行自拍以验证身份，请确保光线充足且面部清晰可见。',
    },
    {
      'icon': Icons.phonelink_off,
      'title': '诚信考试',
      'description': '请独立完成考试，不得使用手机或其他设备查询答案。',
    },
    {
      'icon': Icons.help_outline,
      'title': '答题要求',
      'description': '客观题自动评分，主观题需等待教师评分后才能查看完整结果。',
    },
    {
      'icon': Icons.save,
      'title': '自动保存',
      'description': '考试过程中的答案会自动保存，考试结束后将自动提交。',
    },
    {
      'icon': Icons.warning_amber,
      'title': '注意事项',
      'description': '考试中途退出将视为提交考试，请谨慎操作。',
    },
  ];

  @override
  Widget build(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return WillPopScope(
      onWillPop: () async {
        // 显示确认对话框
        final shouldPop = await showDialog<bool>(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('确认返回?'),
            content: const Text('返回将不会开始考试，确定要离开此页面吗?'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(false), // 不离开
                child: const Text('取消'),
              ),
              ElevatedButton(
                onPressed: () => Navigator.of(context).pop(true), // 确认离开
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                ),
                child: const Text('确认返回'),
              ),
            ],
          ),
        ) ?? false; // 默认不离开

        // 如果用户确认返回，手动pop并传递false值表示没有开始考试
        if (shouldPop) {
          Navigator.of(context).pop(false);
          return false; // 阻止默认的pop行为，因为我们已经手动pop了
        }
        return false; // 不允许返回
      },
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            '考试须知',
            style: TextStyle(
              fontSize: 18.0,
              fontWeight: FontWeight.bold,
              color: Colors.white,
            ),
          ),
          backgroundColor: Colors.blue.shade800,
          foregroundColor: Colors.white,
        ),
        body: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                child: Padding(
                  padding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 16)),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 考试标题和基本信息
                      _buildExamHeader(context),
                      
                      SizedBox(height: ResponsiveUtil.scaleHeight(context, 24)),
                      
                      // 考试规则标题
                      Text(
                        '考试规则',
                        style: ResponsiveUtil.getBalancedTextStyle(
                          context,
                          fontSize: isTablet ? 22 : 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      
                      SizedBox(height: ResponsiveUtil.scaleHeight(context, 16)),
                      
                      // 考试规则列表
                      ...List.generate(_examRules.length, (index) => 
                        _buildRuleItem(
                          context: context,
                          icon: _examRules[index]['icon'] as IconData,
                          title: _examRules[index]['title'] as String,
                          description: _examRules[index]['description'] as String,
                        ),
                      ),
                      
                      SizedBox(height: ResponsiveUtil.scaleHeight(context, 24)),
                      
                      // 自定义规则（如果考试有特定要求）
                      if (widget.exam.requirements != null && widget.exam.requirements!.isNotEmpty)
                        _buildCustomRequirements(context),
                      
                      SizedBox(height: ResponsiveUtil.scaleHeight(context, 32)),
                      
                      // 自拍提示
                      _buildPhotoRequirementBox(context),
                      
                      SizedBox(height: ResponsiveUtil.scaleHeight(context, 16)),
                      
                      // 同意规则复选框
                      _buildAcceptCheckbox(context),
                    ],
                  ),
                ),
              ),
            ),
            
            // 底部按钮
            _buildBottomButtons(context),
          ],
        ),
      ),
    );
  }
  
  // 考试标题和基本信息
  Widget _buildExamHeader(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 16)),
      decoration: BoxDecoration(
        color: Colors.blue.shade50,
        borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
        border: Border.all(color: Colors.blue.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            widget.exam.title,
            style: ResponsiveUtil.getBalancedTextStyle(
              context,
              fontSize: isTablet ? 24 : 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: ResponsiveUtil.scaleHeight(context, 8)),
          Text(
            widget.exam.description,
            style: ResponsiveUtil.getBalancedTextStyle(
              context,
              fontSize: isTablet ? 16 : 14,
              color: Colors.grey.shade800,
            ),
          ),
          SizedBox(height: ResponsiveUtil.scaleHeight(context, 16)),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              _buildExamInfoItem(
                context: context,
                icon: Icons.timer,
                label: '${widget.exam.duration}分钟',
              ),
              _buildExamInfoItem(
                context: context,
                icon: Icons.question_answer,
                label: '${widget.exam.questions.length}题',
              ),
              _buildExamInfoItem(
                context: context,
                icon: Icons.score,
                label: '${widget.exam.totalScore}分',
              ),
            ],
          ),
        ],
      ),
    );
  }
  
  // 考试信息项
  Widget _buildExamInfoItem({
    required BuildContext context,
    required IconData icon,
    required String label,
  }) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Row(
      children: [
        Icon(
          icon,
          size: ResponsiveUtil.getIconSize(context, base: 0.8 * 24),
          color: Colors.blue.shade700,
        ),
        SizedBox(width: ResponsiveUtil.scaleWidth(context, 4)),
        Text(
          label,
          style: ResponsiveUtil.getBalancedTextStyle(
            context,
            fontSize: isTablet ? 16 : 14,
            fontWeight: FontWeight.w500,
          ),
        ),
      ],
    );
  }
  
  // 考试规则项
  Widget _buildRuleItem({
    required BuildContext context,
    required IconData icon,
    required String title,
    required String description,
  }) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Container(
      margin: EdgeInsets.only(bottom: ResponsiveUtil.scaleHeight(context, 16)),
      padding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 16)),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
        border: Border.all(color: Colors.grey.shade300),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(
            icon,
            size: ResponsiveUtil.getIconSize(context, base: 1.2 * 24),
            color: Colors.blue.shade700,
          ),
          SizedBox(width: ResponsiveUtil.scaleWidth(context, 16)),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: ResponsiveUtil.getBalancedTextStyle(
                    context,
                    fontSize: isTablet ? 18 : 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: ResponsiveUtil.scaleHeight(context, 4)),
                Text(
                  description,
                  style: ResponsiveUtil.getBalancedTextStyle(
                    context,
                    fontSize: isTablet ? 16 : 14,
                    color: Colors.grey.shade800,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  // 自定义要求
  Widget _buildCustomRequirements(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '考试特别要求',
          style: ResponsiveUtil.getBalancedTextStyle(
            context,
            fontSize: isTablet ? 22 : 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(height: ResponsiveUtil.scaleHeight(context, 16)),
        Container(
          width: double.infinity,
          padding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 16)),
          decoration: BoxDecoration(
            color: Colors.amber.shade50,
            borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
            border: Border.all(color: Colors.amber.shade200),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: widget.exam.requirements!.map((requirement) => 
              Padding(
                padding: EdgeInsets.only(bottom: ResponsiveUtil.scaleHeight(context, 8)),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Icon(
                      Icons.check_circle,
                      size: ResponsiveUtil.getIconSize(context, base: 0.8 * 24),
                      color: Colors.amber.shade800,
                    ),
                    SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
                    Expanded(
                      child: Text(
                        requirement,
                        style: ResponsiveUtil.getBalancedTextStyle(
                          context,
                          fontSize: isTablet ? 16 : 14,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ).toList(),
          ),
        ),
      ],
    );
  }
  
  // 自拍要求提示框
  Widget _buildPhotoRequirementBox(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 16)),
      decoration: BoxDecoration(
        color: Colors.orange.shade50,
        borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
        border: Border.all(color: Colors.orange.shade300, width: 2),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Icon(
            Icons.camera_enhance,
            size: ResponsiveUtil.getIconSize(context, base: 1.2 * 24),
            color: Colors.orange.shade700,
          ),
          SizedBox(width: ResponsiveUtil.scaleWidth(context, 16)),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '重要提示：需要自拍验证',
                  style: ResponsiveUtil.getBalancedTextStyle(
                    context,
                    fontSize: isTablet ? 18 : 16,
                    fontWeight: FontWeight.bold,
                    color: Colors.orange.shade800,
                  ),
                ),
                SizedBox(height: ResponsiveUtil.scaleHeight(context, 8)),
                Text(
                  '点击"开始考试"按钮后，系统将要求您完成一张自拍照片用于身份验证。请确保您的面部清晰可见，且照片质量良好。您可以查看照片并选择重拍，直到满意为止。',
                  style: ResponsiveUtil.getBalancedTextStyle(
                    context,
                    fontSize: isTablet ? 16 : 14,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  // 同意规则复选框
  Widget _buildAcceptCheckbox(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Container(
      decoration: BoxDecoration(
        color: Colors.grey.shade100,
        borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
        border: Border.all(color: Colors.grey.shade300),
      ),
      padding: EdgeInsets.all(ResponsiveUtil.scaleWidth(context, 16)),
      child: Row(
        children: [
          Transform.scale(
            scale: isTablet ? 1.2 : 1.0,
            child: Checkbox(
              value: _rulesAccepted,
              activeColor: Colors.blue.shade700,
              onChanged: (value) {
                setState(() {
                  _rulesAccepted = value ?? false;
                });
              },
            ),
          ),
          SizedBox(width: ResponsiveUtil.scaleWidth(context, 8)),
          Expanded(
            child: Text(
              '我已阅读并理解以上考试规则，承诺将遵守考试纪律，独立完成考试。',
              style: ResponsiveUtil.getBalancedTextStyle(
                context,
                fontSize: isTablet ? 16 : 14,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  // 底部按钮
  Widget _buildBottomButtons(BuildContext context) {
    final bool isTablet = ResponsiveUtil.isTablet(context);
    
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: ResponsiveUtil.scaleWidth(context, 16),
        vertical: ResponsiveUtil.scaleHeight(context, 16),
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 3,
            offset: Offset(0, -1),
          ),
        ],
      ),
      child: Row(
        children: [
          Expanded(
            child: OutlinedButton(
              onPressed: () => Navigator.pop(context, false),
              style: OutlinedButton.styleFrom(
                padding: EdgeInsets.symmetric(
                  vertical: ResponsiveUtil.scaleHeight(context, isTablet ? 16 : 12),
                ),
                side: BorderSide(color: Colors.blue.shade700),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
                ),
              ),
              child: Text(
                '返回',
                style: ResponsiveUtil.getBalancedTextStyle(
                  context,
                  fontSize: isTablet ? 16 : 14,
                  color: Colors.blue.shade700,
                ),
              ),
            ),
          ),
          SizedBox(width: ResponsiveUtil.scaleWidth(context, 16)),
          Expanded(
            child: ElevatedButton(
              onPressed: _rulesAccepted 
                ? () => _startExam() 
                : null,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue.shade700,
                padding: EdgeInsets.symmetric(
                  vertical: ResponsiveUtil.scaleHeight(context, isTablet ? 16 : 12),
                ),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(ResponsiveUtil.getBorderRadius(context)),
                ),
                disabledBackgroundColor: Colors.grey.shade400,
              ),
              child: Text(
                '开始考试',
                style: ResponsiveUtil.getBalancedTextStyle(
                  context,
                  fontSize: isTablet ? 16 : 14,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
  
  // 开始考试
  void _startExam() async {
    final currentUser = UserData.currentUser;
    if (currentUser == null) return;
    // 检查本地是否有未完成的考试进度
    final localState = await ExamStateService.getExamState(widget.exam.id, currentUser.id);
    if (localState != null && localState.status == ExamStatus.inProgress) {
      // 弹窗提示用户
      final action = await showDialog<String>(
        context: context,
        barrierDismissible: false,
        builder: (context) => AlertDialog(
          title: Text('恢复考试'),
          content: Text('检测到上次未完成的考试，是否恢复上次进度？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop('restart'),
              child: Text('重新开始'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.of(context).pop('resume'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
              ),
              child: Text('恢复'),
            ),
          ],
        ),
      );
      if (action == 'resume') {
        // 直接进入考试，带上本地进度
        await _captureAndConfirmPhoto(resumeState: localState);
        return;
      } else if (action == 'restart') {
        // 清除本地进度
        await ExamStateService.removeExamState(widget.exam.id, currentUser.id);
      } else {
        // 用户取消
        return;
      }
    }
    // 正常流程
    await _captureAndConfirmPhoto();
  }
  
  // 拍照并确认
  Future<void> _captureAndConfirmPhoto({ExamState? resumeState}) async {
    File? avatarFile = await ImageService.takePhoto();
    if (avatarFile == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('必须拍照上传头像才能开始考试'), backgroundColor: Colors.red),
      );
      return;
    }
    // 显示照片确认对话框
    bool? confirmed = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('确认照片'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('请确认您的照片清晰可见：'),
              SizedBox(height: 16),
              ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: Image.file(
                  avatarFile,
                  height: 200,
                  fit: BoxFit.cover,
                ),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(false); // 不确认，重拍
              },
              child: Text('重新拍照'),
            ),
            ElevatedButton(
              onPressed: () {
                Navigator.of(context).pop(true); // 确认
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
              ),
              child: Text('确认并进入考试'),
            ),
          ],
        );
      },
    );
    if (confirmed == true) {
      // 用户确认照片，开始考试
      ExamState? examState;
      if (resumeState != null) {
        examState = resumeState;
      } else {
        examState = await ExamStateService.startExam(
      widget.exam.id, 
          widget.exam.duration,
    );
      }
      if (mounted) {
        // 直接替换当前页面为考试页面，避免触发不必要的刷新
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => ExamScreen(
              exam: widget.exam,
              initialState: examState,
              avatarPath: avatarFile.path,
            ),
          ),
        );
      }
    } else {
      // 用户选择重拍，递归调用本方法
      await _captureAndConfirmPhoto(resumeState: resumeState);
    }
  }
}
